//////////////////////////////
// DFRobot SEN0014
const int InfraredSensorPin = 0;

short get_range_sensor_gp2ya02(const int iInfraPin, const int iCount=5, const int iDelay=0, const float fBeamPrecision=0, const float fMin=0, const float fMax=0)
{
  float fValMin = -1, fValMax = -1;
  float fDistance = 0;
  float fCount = 0;
  boolean bLimitRange = (fMax>fMin)?true:false;
  boolean bUsePrecision = (fBeamPrecision>0)?true:false;

  for(int i=0; i<iCount; i++)
  {
    if(iDelay>0) delay(iDelay);

    const float fScale = 5.0f/1024.0f;    // value from sensor * (5/1024) - if running 3.3.volts then change 5 to 3.3
    int iAnalogValue = analogRead(iInfraPin);
    float fVolts = iAnalogValue*fScale;

    // worked out from graph 65 = theretical distance / (1/Volts)S - luckylarry.co.uk
    float fVal = 65.0f*pow(fVolts, -1.10f); 
    if(!bLimitRange || (bLimitRange && fVal>=fMin && fVal<=fMax))
    {
      if(bUsePrecision)
      {
        if(fValMax==-1 || fVal>fValMax) fValMax = fVal;      
        else if(fValMin==-1 || fVal<fValMin) fValMin = fVal;
      }
      fDistance += fVal;
      fCount ++;
    }
  }

  // Sum result
  if(fCount>1)
  {
    fDistance /= fCount;

    // ecart trop important = bad result
    if(bUsePrecision && abs(fValMax)-abs(fValMin)>((fMax-fMin)*fBeamPrecision))
      return bLimitRange?fMax:-1;
  }

  if(bLimitRange)
  {
    // out of range ?
    if(fCount==0 || fDistance>fMax) fDistance = fMax;
    else if(fDistance<fMin) fDistance = fMin;
  }

  // retour en cm
  return (short)fDistance;
}

void setup()
{
  Serial.begin(9600);
  Serial.println("Start!");  
  pinMode(InfraredSensorPin,INPUT);
}

void loop()
{
  Serial.print("Dist :");
  //int distance = get_range_sensor_gp2ya02(InfraredSensorPin);
  //int distance = get_range_sensor_gp2ya02(InfraredSensorPin, 10, 5);
  //int distance = get_range_sensor_gp2ya02(InfraredSensorPin, 10, 10, 0.15, 0, 0);
  //int distance = get_range_sensor_gp2ya02(InfraredSensorPin, 5, 5, 0.15, 20, 150);
  int distance = get_range_sensor_gp2ya02(InfraredSensorPin, 10, 7, 0.10, 25, 145);
  Serial.print(distance, DEC);
  Serial.println(" cm");  
  delay(250);
}
